package com.lhl.jwt.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @className: DateConfig
 * @description: TODO 类描述
 * @author: king
 * @date: 2020-09-07 17:41
 **/
@JsonComponent
@Slf4j
public class DateConfig {
    private static SimpleDateFormat dateFormat =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") {
                @Override
                public Date parse(String source) throws ParseException {
                    try {
                        if (StringUtils.isEmpty(source)) {
                            return null;
                        }
                        return super.parse(source);
                    } catch (Exception e) {
                        return new StdDateFormat().parse(source);
                    }
                }
            };

    /**
     * @Description: 对象转换成字符串
     * @Author: king
     * @Date: 2020-05-21 17:25
     **/
    public static class DateJsonSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(
                Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                throws IOException {

            jsonGenerator.writeString(dateFormat.format(date));
        }
    }

    /**
     * @Description: 解析日期字符串
     * @Author: king
     * @Date: 2020-05-21 17:25
     **/
    public static class DateJsonDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
                throws IOException, JsonProcessingException {
            try {
                log.debug("jsonParser.getText()=={}", jsonParser.getText());
                return dateFormat.parse(jsonParser.getText());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }
}